#include "tcpserver.h"
#include "ui_tcpserver.h"

tcpserver::tcpserver(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::tcpserver)
{
    ui->setupUi(this);

    tcpServer = NULL;
    tcpSocket = NULL;

    tcpServer = new QTcpServer(this);
    tcpServer->listen(QHostAddress::Any,8086);

    connect(tcpServer,&QTcpServer::newConnection,
            [=]()
    {
        tcpSocket = tcpServer->nextPendingConnection();
        QString ip = tcpSocket->peerAddress().toString();
        qint16 port = tcpSocket->peerPort();
        QString temp = QString("[%1:%2]:成功连接").arg(ip).arg(port);
        emit connectsuccess();

        ui->textEdit_Recv->setText(temp);

        connect(tcpSocket,&QTcpSocket::readyRead,
                [=]()
        {
            QByteArray arr = tcpSocket->readAll();
            ui->textEdit_Recv->append(arr);
            qstr = QString::fromStdString(arr.toStdString());
            emit sendsignal();
        }
                );
    }
            );
}

tcpserver::~tcpserver()
{
    delete ui;
}

void tcpserver::on_pushButton_clicked()
{
    if (tcpSocket != NULL) {
        QString str = this->ui->textEdit_Send->toPlainText();
        tcpSocket->write(str.toUtf8().data());
    }
}

void tcpserver::on_pushButton_2_clicked()
{
    if (tcpSocket != NULL) {
        tcpSocket->disconnectFromHost();
        tcpSocket->close();
        tcpSocket = NULL;
    }
}

void tcpserver::SetPort(int port) {
    this->s_port = port;
}
